package quattrow;

import dblib.DB;
import dblib.PDM;
import java.awt.Color;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class LogsDialog extends javax.swing.JDialog {

    public LogsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setMinimumSize(this.getSize());

        DefaultTableModel tablemodel1 = new DefaultTableModel(
                new Object[][]{},
                new String[]{"Date", "HostID", "Class", "Log text"}) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        jTable1.setModel(tablemodel1);

        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(tablemodel1);
        jTable1.setRowSorter(sorter);

        ListSelectionListener lsl = new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (jTable1.getSelectedRow() > -1) {
                    Object[] o1 = (Object[]) jTable1.getValueAt(jTable1.getSelectedRow(), 0);
                    Object[] o2 = (Object[]) jTable1.getValueAt(jTable1.getSelectedRow(), 1);
                    Object[] o3 = (Object[]) jTable1.getValueAt(jTable1.getSelectedRow(), 2);
                    Object[] o4 = (Object[]) jTable1.getValueAt(jTable1.getSelectedRow(), 3);
                    jLabel2.setText("Date: " + o1[0] + " / HostID: " + o2[0] + " / Class: " + o3[0]);
                    jLabel3.setText("Log text: " + o4[0]);
                }
            }
        };

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(Integer.parseInt(Vars.prop.getProperty("LogW1")));
        jTable1.getColumnModel().getColumn(0).setCellRenderer(new jTableCellRenderer());
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(Integer.parseInt(Vars.prop.getProperty("LogW2")));
        jTable1.getColumnModel().getColumn(1).setCellRenderer(new jTableCellRenderer());
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(Integer.parseInt(Vars.prop.getProperty("LogW3")));
        jTable1.getColumnModel().getColumn(2).setCellRenderer(new jTableCellRenderer());
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(Integer.parseInt(Vars.prop.getProperty("LogW4")));
        jTable1.getColumnModel().getColumn(3).setCellRenderer(new jTableCellRenderer());

        jTable1.getSelectionModel().addListSelectionListener(lsl);

        jTextField1.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent de) {
                filterTable();
            }

            @Override
            public void removeUpdate(DocumentEvent de) {
                filterTable();
            }

            @Override
            public void changedUpdate(DocumentEvent de) {
                filterTable();
            }
        });

        RefreshTable();
    }

    private void filterTable() {
        RowFilter<DefaultTableModel, Integer> rowfilter = new RowFilter<DefaultTableModel, Integer>() {

            @Override
            public boolean include(RowFilter.Entry<? extends DefaultTableModel, ? extends Integer> entry) {
                Object[] o1 = (Object[]) entry.getValue(0);
                Object[] o2 = (Object[]) entry.getValue(1);
                Object[] o3 = (Object[]) entry.getValue(2);
                Object[] o4 = (Object[]) entry.getValue(3);

                String str = o1[0] + " " + o2[0] + " " + o3[0] + " " + o4[0];
                str = str.toLowerCase();
                str = str.trim();
                str = str.replaceAll("   ", " ");
                str = str.replaceAll("-", "");

                String[] strs = jTextField1.getText().toLowerCase().trim().split(" ");

                boolean ch = false;
                int chi = (int) o1[1];
                if (chi == 1 && jCheckBox1.isSelected()) {
                    ch = true;
                }
                if (chi == 2 && jCheckBox2.isSelected()) {
                    ch = true;
                }
                if (chi == 3 && jCheckBox3.isSelected()) {
                    ch = true;
                }

                if (ch) {
                    for (String s : strs) {
                        if (str.contains(s)) {
                            return true;
                        }
                    }
                }

                return false;
            }
        };
        TableRowSorter<DefaultTableModel> sorter = (TableRowSorter<DefaultTableModel>) jTable1.getRowSorter();
        sorter.setRowFilter(rowfilter);
    }

    private class jTableCellRenderer extends DefaultTableCellRenderer {

        @Override
        protected void setValue(Object value) {
            Object[] val = (Object[]) value;
            String strval = (value == null) ? "" : (String) val[0];
            int logtype = (int) val[1];
            switch (logtype) {
                case 1:
                    setForeground(new Color(230, 0, 0));
                    break;
                case 2:
                    //setForeground(new Color(170, 130, 0));
                    setForeground(new Color(128, 15, 15));
                    break;
                case 3:
                    setForeground(new Color(0, 170, 50));
                    break;
                default:
                    setForeground(Color.BLACK);
                    break;
            }
            setText(strval);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jCheckBox3 = new javax.swing.JCheckBox();
        jButton3 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Просмотр логов");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jButton1.setText("Закрыть");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Фильтр:");

        jButton2.setText("<<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jCheckBox1.setSelected(true);
        jCheckBox1.setText("1");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jCheckBox2.setSelected(true);
        jCheckBox2.setText("2");
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        jCheckBox3.setSelected(true);
        jCheckBox3.setText("3");
        jCheckBox3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox3ActionPerformed(evt);
            }
        });

        jButton3.setText("Удалить запись");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Date: **.**.**** **:**:** / HostID: ******* / Class: *******");

        jLabel3.setText("Log text: *******");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton4.setText("Обновить");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1076, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jCheckBox1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jCheckBox2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jCheckBox3))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 1076, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCheckBox1)
                    .addComponent(jCheckBox2)
                    .addComponent(jCheckBox3)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Vars.prop.setProperty("LogW1", String.valueOf(jTable1.getColumnModel().getColumn(0).getWidth()));
        Vars.prop.setProperty("LogW2", String.valueOf(jTable1.getColumnModel().getColumn(1).getWidth()));
        Vars.prop.setProperty("LogW3", String.valueOf(jTable1.getColumnModel().getColumn(2).getWidth()));
        Vars.prop.setProperty("LogW4", String.valueOf(jTable1.getColumnModel().getColumn(3).getWidth()));
        Vars.SaveProperties();
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        Vars.prop.setProperty("LogW1", String.valueOf(jTable1.getColumnModel().getColumn(0).getWidth()));
        Vars.prop.setProperty("LogW2", String.valueOf(jTable1.getColumnModel().getColumn(1).getWidth()));
        Vars.prop.setProperty("LogW3", String.valueOf(jTable1.getColumnModel().getColumn(2).getWidth()));
        Vars.prop.setProperty("LogW4", String.valueOf(jTable1.getColumnModel().getColumn(3).getWidth()));
        Vars.SaveProperties();
    }//GEN-LAST:event_formWindowClosing

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        jTextField1.setText("");
        jTextField1.requestFocus();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        filterTable();
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        filterTable();
    }//GEN-LAST:event_jCheckBox2ActionPerformed

    private void jCheckBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox3ActionPerformed
        filterTable();
    }//GEN-LAST:event_jCheckBox3ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        PDM pdm = new PDM();
        for (int selrow : jTable1.getSelectedRows()) {
            Object[] o = (Object[]) jTable1.getValueAt(selrow, 0);
            pdm.executeNonQueryUpdate("log", "UPDATE logs SET `hide` = true WHERE k = " + o[2]);
        }
        RefreshTable();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        RefreshTable();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void RefreshTable() {
        DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
        while (tm.getRowCount() > 0) {
            tm.removeRow(0);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

        PDM pdm = new PDM();
        ResultSet rs = pdm.getResultSet("log", "SELECT k, hostid, logtype, `class`, logtext, dt FROM logs WHERE hide = false ORDER BY k DESC");
        try {
            while (rs.next()) {
                int k = rs.getInt("k");
                int logtype = rs.getInt("logtype");
                Object[] rowdata = new Object[4];
                rowdata[0] = new Object[]{sdf.format(DB.getCalendarFromTime(rs.getTimestamp("dt")).getTime()), logtype, k};
                rowdata[1] = new Object[]{DB.getStringFromHex(rs.getString("hostid")), logtype};
                rowdata[2] = new Object[]{DB.getStringFromHex(rs.getString("class")), logtype};
                rowdata[3] = new Object[]{DB.getStringFromHex(rs.getString("logtext")), logtype};
                tm.addRow(rowdata);
            }
        } catch (SQLException ex) {
            Logger.getLogger(LogsDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
        pdm.closeResultSet();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
